/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.web.util.HtmlUtils;

import com.google.common.base.Strings;

/**
 * <Briefly describing the purpose of the class/interface...>
 * 
 */
public final class StringUtils {
	private StringUtils() {}

	public static List<String> fromStrToList(String source, String delimiter) {
        List<String> list = new ArrayList<>();
        if (!Strings.isNullOrEmpty(source)) {
            StringTokenizer tokenizer = new StringTokenizer(source, delimiter);
            while (tokenizer.hasMoreTokens()) {
                list.add(tokenizer.nextToken());
            }
        }
        return list;
    }

    public static String fromListToStr(List<String> source, String delimiter) {
        StringBuffer result = new StringBuffer();
        if (source != null && source.size() > 0) {
            for (String aSource : source) {
                if (result.length() > 0) {
                    result.append(delimiter);
                }
                result.append(aSource);
            }
        }
        return result.toString();
    }
    
    public static String appendStr(String str1, String str2, String connector) {
        return (str1 != null && str1.trim().length() > 0 ? (str2 != null && str2.trim().length() > 0 ? str1 + connector + str2 : str1) : str2);
    }
    
    /**
     * @deprecated Use {@link StringListUtils#aggregate(List, List)} instead
     */
    @Deprecated
    public static List<String> addListToNewList(List<String> list1, List<String> list2) {
        List<String> list = new ArrayList<>();
        if (list1 != null) {
            list.addAll(list1);
        } 
        if (list2 != null){
            list.addAll(list2);
        }
        return list;
    }
    
    /**
     * @deprecated Use {@link Strings#isNullOrEmpty(String)} instead
     */
    @Deprecated
    public static boolean isNotEmpty(String source) {
    	return !isNullOrEmpty(source);
    }
    
    /**
     * @deprecated Use {@link Strings#isNullOrEmpty(String)} instead
     */
    @Deprecated
    public static boolean isNullOrEmpty(String source) {
    	return Strings.isNullOrEmpty(source);
    }
    
    public static boolean parseBoolean(String text) {
    	return toBoolean(text);
    }
    
    @Deprecated
    public static String[] parseStringArray(String text) {
        return text.split("[\\s\\t]*,[\\s\\t]*");
    }
    
    public static String toHexString(byte[] data) {
        StringBuffer hex = new StringBuffer();
        for (int b : data) {
            hex.append(Integer.toHexString(0xFF & b));
        }
        return hex.toString();
    }
    
    public static boolean toBoolean(String value) {
        return "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value);
    }

    /**
     * @deprecated Use {@link HTMLInputFilter} instead
     */
    @Deprecated
    public static String cleanTagsInContent(String content, String... tags) {
        StringBuilder regex = new StringBuilder();
        for (int i=0; i<tags.length; i++) {
            regex.append(String.format("(<%1$s[^>]*>)|(</%1$s>)", tags[i]));
            if (i < tags.length - 1) {
                regex.append('|');
            }
        }
        
        Pattern pattern = Pattern.compile(regex.toString(), Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        String result = matcher.replaceAll("");
                
        return result;
    }
    
    /**
     * @deprecated Use {@link HtmlUtils#htmlEscape(String)} instead
     */
    @Deprecated
    public static String toHTML(String str) {
    	if (str == null) {
    		return null;
    	}
    	return str.replaceAll("<", "&lt;")
    			.replaceAll(">", "&gt;")
    			.replaceAll("(\r)?\n", "<br/>");
    	
    }
    
    public static String inputStreamAsString(InputStream stream) throws IOException {
    	BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    	StringBuilder sb = new StringBuilder();
    	String line = null;

    	while ((line = br.readLine()) != null) {
    		sb.append(line + "\n");
    	}

    	br.close();
    	return sb.toString();
    }
    
    /**
     * @deprecated Use {@link StringListUtils#stringToList(String)} instead
     */
    @Deprecated
    public static Collection<String> commaDelimitedListToSet(String... items) {
    	List<String> arr = new ArrayList<>();
    	for (String item : items) {
    		arr.add(item);
		}
    	return arr;
    }
    
    /**
     * @deprecated
     */
    @Deprecated
    public static boolean isLongText(String str, int limitedSize) {
    	if(str == null || str.length() <= limitedSize) {
	        return false;
	    }
	    
	    return true;
    }
    
    /**
     * @deprecated
     */
    @Deprecated
    public static String fromListLongToStr(List<Long> source, String connector) {
        StringBuffer result = new StringBuffer();
        if (source != null && source.size() > 0) {
            for (Long aSource : source) {
                if (result.length() > 0) {
                    result.append(connector);
                }
                result.append(aSource);
            }
        }
        return result.toString();
    }
    
	/**
	 * Converts a stackTrace from an Exception into a String
	 * @param e Exception to convert
	 * @return a string 
	 */
	public static String stackToString(Exception e) {
		  try {
		    StringWriter sw = new StringWriter();
		    PrintWriter pw = new PrintWriter(sw);
		    e.printStackTrace(pw);
		    return "------\r\n" + sw.toString() + "------\r\n";
		  } catch(Exception e2) {
		    return "Bad StackTrace : " + e2.getMessage();
		  }
	} 
    
}
